﻿using System.Management;

namespace Testing.Helpers.Computer
{
    /// <summary>
    /// Helper for enable/disable network adapter.
    /// </summary>
    public class NetworkAdapterHelper
    {
        private readonly string _netConnectionId;

        /// <summary>
        /// Initializes a new instance of the <see cref="NetworkAdapterHelper"/> class.
        /// </summary>
        /// <param name="netConnectionId">Network connection Id.</param>
        public NetworkAdapterHelper(string netConnectionId)
        {
            this._netConnectionId = netConnectionId;
        }
        /// <summary>
        /// Enables network adapter.
        /// </summary>
        public void EnableNetworkAdapter()
        {
            this.ChangeNetworkAdapter("Enable");
        }

        /// <summary>
        /// Disables network adapter.
        /// </summary>
        public void DisableNetworkAdapter()
        {
            this.ChangeNetworkAdapter("Disable");
        }

        private void ChangeNetworkAdapter(string state)
        {
            var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
            var searchProcedure = new ManagementObjectSearcher(wmiQuery);
            foreach (ManagementObject item in searchProcedure.Get())
            {
                if (((string)item["NetConnectionId"]) == this._netConnectionId)
                {
                    item.InvokeMethod(state, null);
                }
            }
        }
    }
}
